<route lang="yaml">
meta:
  title: 报修数据
</route>

<script setup>
import axios from 'axios'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

// State variables
const tableData = ref([])
const stateOptions = [
  { value: '-1', label: '全部' },
  { value: '1', label: '待处理' },
  { value: '2', label: '已驳回' },
  { value: '3', label: '留观中' },
  { value: '4', label: '已处置' },
]
const typeOptions = [
  { value: '3', label: '全部' },
  { value: '1', label: '预警' },
  { value: '2', label: '故障' },
]

const uniqueRegions = computed(() => [...new Set(tableData.value.map(item => item.region))])
const uniqueUnits = computed(() => [...new Set(tableData.value.map(item => item.unit))])

const selectedRegion = ref('')
const selectedType = ref()
const selectedState = ref()
const dialogTitle = ref('')
const totalNum = ref(0)

const currentPage = ref(1)
const pageSize = 10
const workOrderCreateRemarks = ref('')
const feedbackInfo = ref('')

const isDialogVisible = ref(false)

function handlePageChange(page) {
  currentPage.value = page
  fetchData({ pageNum: currentPage.value })
}

function changeObserve(row) {
  row.observe = (row.observe + 1) % 2
}

function handle(row) {
  feedbackInfo.value = row
  dialogTitle.value = '处置'
  isDialogVisible.value = true
}

function reject(row) {
  feedbackInfo.value = row
  dialogTitle.value = '驳回'
  isDialogVisible.value = true
}

function liuguan(row) {
  feedbackInfo.value = row
  dialogTitle.value = '留观'
  isDialogVisible.value = true
}

// 修改已读
async function upAppointUnreadBackend(feedbackCode) {
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/upAppointUnreadBackend', {
      feedbackCode,
    })
    if (response.data.code === 200) {
      console.log('已读：', response.data)
      await fetchData({})
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
const router = useRouter()
function openReportPage(row) {
  const to = router.resolve({
    name: 'report-details',
    params: { id: row.feedbackCode },
  })
  // upAppointUnreadBackend(row.feedbackCode)
  const httpUrl = to.href.replace(/^https:\/\//, 'http://')
  console.log('Generated URL:', httpUrl) // 打印完整的地址
  window.open(httpUrl, '_blank')
  // window.open(to.href, '_blank')
}

async function createWorkOrder() {
  const { feedbackCode, customerCode, customerName, customerUserName, customerUserPhone, feedbackContent, feedbackAddress, feedbackCity, feedbackProvince, feedbackRegion, feedbackLongitude, feedbackLatitude, createDate, feedbackType, feedbackImgFile, feedbackVideoFile, feedbackVoiceFile } = feedbackInfo.value
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/workOrder/createWorkOrder', {
      feedbackCode,
      customerCode,
      customerName,
      customerUserName,
      customerUserPhone,
      adminUserCode: 'ADMIN-USER20241031211423',
      workOrderContent: feedbackContent,
      workOrderImgFile: feedbackImgFile,
      feedbackDate: createDate,
      feedbackProvince,
      feedbackCity,
      feedbackRegion,
      feedbackAddress,
      feedbackLongitude,
      feedbackLatitude,
      feedbackType,
      workOrderVideoFile: feedbackVideoFile,
      workOrderVoiceFile: feedbackVoiceFile,
      workOrderCreateRemarks: workOrderCreateRemarks.value,
    })

    if (response.data.code === 200) {
      console.log('生成工单', response.data)
      window.location.reload()
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}

async function confirmAdd() {
  let feedbackState = 4
  if (dialogTitle.value === '处置') {
    feedbackState = 4
  }
  else if (dialogTitle.value === '驳回') {
    feedbackState = 2
  }
  else {
    feedbackState = 3
  }
  isDialogVisible.value = false
  const { feedbackCode } = feedbackInfo.value
  console.log('feedbackState', feedbackState)

  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/stateUp', {
      feedbackCode,
      feedbackState,
      feedbackRemarks: workOrderCreateRemarks.value,
    })

    if (response.data.code === 200) {
      if (feedbackState === 4) {
        createWorkOrder()
      }
      else {
        window.location.reload()
      }
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}

async function fetchData({ pageNum = '1', psCustomerCode = null }) {
  console.log('selectedType', selectedType.value)
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/findAllByConditionToObserveNew', {
      pageNum,
      pageSize,
      // psCustomerCode,
      feedbackRegion: selectedRegion.value,
      feedbackType: selectedType.value,
      // feedbackState: selectedState.value,
      feedbackClassification: 2,
    })

    if (response.data) {
      console.log('报修数据：', response.data)
      tableData.value = response.data.data.rows
      totalNum.value = response.data.data.total
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}

function formatFeedbackType(row, column, cellValue) {
  if (cellValue === 1) {
    return '预警'
  }
  else if (cellValue === 2) {
    return '故障'
  }
  else {
    return '未知'
  }
}

function resetSelection() {
  workOrderCreateRemarks.value = null
}
function resetSelectData() {
  selectedType.value = typeOptions[0].value
  selectedState.value = stateOptions[0].value
}

onMounted(() => {
  resetSelectData()
  fetchData({})
})
</script>

<template>
  <div class="dashboard">
    <!-- 标题栏 -->
    <div class="header">
      故障上报管理
    </div>

    <!-- 筛选区域 -->
    <el-row :gutter="20" class="filter-row">
      <el-col :span="4">
        <el-input v-model="selectedRegion" style="width: 240px;" placeholder="请输入区域" />
      </el-col>
      <el-col :span="4">
        <el-select v-model="selectedType" placeholder="请选择类型" clearable>
          <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="selectedState" placeholder="请选择状态" clearable>
          <el-option v-for="state in stateOptions" :key="state.value" :label="state.label" :value="state.value" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" class="search-button" @click="fetchData({})">
          搜索
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="tableData" border class="table" style="width: 100%; cursor: pointer;" @row-click="openReportPage">
      <el-table-column prop="customerName" label="上报单位" align="center">
        <template #default="{ row }">
          <!-- <span v-if="row.feedbackGlanceServer === 0" class="red-dot"></span> -->
          <span>{{ row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="customerUserName" label="上报人" align="center" />
      <el-table-column prop="feedbackContent" label="故障描述" align="center" />
      <el-table-column prop="createDate" label="上报时间" align="center" />
      <el-table-column prop="feedbackType" label="上报类型" :formatter="formatFeedbackType" align="center" />
      <el-table-column prop="actions" label="操作" align="center">
        <template #default="{ row }">
          <el-button
            type="text" size="small" class="action-button"
            @click="(event) => { event.stopPropagation(); reject(row); }"
          >
            驳回
          </el-button>
          <el-button
            v-if="row.observe === 1" type="text" size="small" class="action-button"
            @click="changeObserve(row)"
          >
            留观
          </el-button>
          <el-button
            v-else type="text" size="small" class="action-button"
            @click="(event) => { event.stopPropagation(); liuguan(row); }"
          >
            留观
          </el-button>
          <el-button
            type="text" size="small" class="action-button"
            @click="(event) => { event.stopPropagation(); handle(row); }"
          >
            处置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <el-dialog v-model="isDialogVisible" :title="dialogTitle" @open="resetSelection">
      <!-- 对话框内容 -->
      <p><strong>请填写备注：</strong></p>
      <el-input v-model="workOrderCreateRemarks" style="width: 600px;" type="textarea" placeholder="请填写备注" clearable />
      <template #footer>
        <el-button @click="isDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmAdd">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <div class="pagination">
        <el-pagination
          size="normal" background layout="prev, pager, next" :total="totalNum" class="mt-4" :current-page="currentPage" :default-page-size="pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.red-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-left: 5px;
  background-color: red;
  border-radius: 50%;
}

.dashboard {
  padding: 20px;
  font-family: Arial, sans-serif;
}

.header {
  display: flex;
  justify-content: center;
  width: 30%;
  padding: 10px 20px;
  margin-bottom: 20px;

  /* 将分页按钮居中 */
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.filter-row {
  margin-bottom: 20px;
}

/* 搜索栏和筛选框样式 */
.search-container {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 20px;
}

.search-button {
  color: white;
  background: linear-gradient(45deg, #3b82f6, #06b6d4);
  border: none;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgb(0 0 0 / 10%);
}

.search-button:hover {
  background: linear-gradient(45deg, #06b6d4, #3b82f6);
}

.table {
  margin-top: 20px;
  overflow: hidden;
  border-radius: 8px;
}

.table >>> .el-table__header-wrapper th {
  padding: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  text-align: center;
  background-color: #f3f4f6;
  border-bottom: 2px solid #e5e7eb;
}

.action-button {
  padding: 4px 8px;
  font-weight: bold;
  color: #3b82f6;
  background-color: antiquewhite;
  border-radius: 5px;
  transition: all 0.2s;
}

.action-button:hover {
  background-color: #5382df;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.pagination {
  bottom: 20px;
  display: flex;

  /* 将分页按钮居中 */
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  margin-top: 20px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 -2px 10px rgb(0 0 0 / 5%);
}

.pagination-wrapper {
  position: fixed;
  bottom: 20px;
  left: 280px;
  z-index: 10;
  align-items: center;
  width: 80%;
  padding: 10px 0;
}
</style>
